package com.lgq.cfw.controller.web;

import com.lgq.cfw.bean.TableMember;
import com.lgq.cfw.bean.TableUser;
import com.lgq.cfw.bean.message.Message;
import com.lgq.cfw.service.MemberService;
import com.lgq.cfw.util.MyStringUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Lin
 * @date 2019-02-15 21:15
 **/
@RestController
@RequestMapping(value = "/web/member")
public class MemberController {

  @Autowired
  MemberService memberService;

  /**
   * 会员注册
   * @param tableMember 封装好的会员对象
   * @param httpServletRequest 获取session
   * @return 处理信息
   */
  @RequestMapping(value = "/register",method = RequestMethod.POST)
  public Message register(TableMember tableMember, HttpServletRequest httpServletRequest){
    //判断是否注册成功
    boolean flag=memberService.register(tableMember);
    if (flag){
      httpServletRequest.getSession().setAttribute("loginName",tableMember.getLoginacct());
      return Message.success("用户注册成功",null);
    }else {
      return Message.fail("该账号已存在",null);
    }
  }

  /**
   * 检查是否存在账号
   * @param loginacct 用户输入的账号
   * @return Ajax Json消息
   */
  @RequestMapping(value = "/checkAccount",method = RequestMethod.POST)
  public Message checkAccount(String loginacct){
    //判断是否已经存在该账号
    boolean flag=memberService.checkAccount(loginacct);
    if (flag){
      return Message.success("该账号可以使用",null);
    }else {
      return Message.fail("该账号已存在",null);
    }
  }

  /**
   * 登录功能
   * @param loginacct 账号
   * @param userpswd 面
   * @param httpServletRequest 存入session
   * @return 处理结果
   */
  @RequestMapping(value = "/login",method = RequestMethod.POST)
  public Message login(String loginacct,String userpswd, HttpServletRequest httpServletRequest){
    boolean flag=memberService.login(loginacct,userpswd);
    if (flag){
      return Message.fail("登录失败",null);
    }else{
      //登录成功放入session域中
      httpServletRequest.getSession().setAttribute("loginName",loginacct);
      return Message.success("登录成功",null);
    }
  }

  @RequestMapping(value = "/getLoginName",method = RequestMethod.GET)
  public Message getLoginName(HttpServletRequest httpServletRequest){
    //获取Session域中的loginName值
    String loginName=(String)httpServletRequest.getSession().getAttribute("loginName");
    //是否返回为空
    if (!MyStringUtils.isEmpty(loginName)){
      return Message.success("处理成功",null).add("loginName",loginName);
    }else{
      return Message.fail("处理失败",null);
    }
  }
}
